import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import { usePermissStore } from '@/store/permiss'
import Home from '../views/home.vue'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/build'
  },
  {
    path: '/',
    name: 'Home',
    component: Home,
    children: [
      {
        path: '/build',
        name: 'build',
        meta: {
          title: '构建'
        },
        component: () => import('@/views/build/index.vue')
      },
      {
        path: '/build-record',
        name: 'build-record',
        meta: {
          title: '构建记录'
        },
        component: () => import('@/views/build-record/index.vue')
      },
      {
        path: '/template',
        name: 'template',
        meta: {
          title: '模板管理'
        },
        component: () => import('@/views/template/index.vue')
      },
      {
        path: '/data-source',
        name: 'data-source',
        meta: {
          title: '数据源管理'
        },
        component: () => import('@/views/data-source/index.vue')
      },
      {
        path: '/test',
        name: 'test',
        meta: {
          title: '测试页面'
        },
        component: () => import('@/views/test/index.vue')
      }
    ]
  },
  {
    path: '/login',
    meta: {
      title: '登录',
      noAuth: true
    },
    component: () => import(/* webpackChunkName: "login" */ '../views/pages/login.vue')
  },
  {
    path: '/register',
    meta: {
      title: '注册',
      noAuth: true
    },
    component: () => import(/* webpackChunkName: "register" */ '../views/pages/register.vue')
  },
  {
    path: '/reset-pwd',
    meta: {
      title: '重置密码',
      noAuth: true
    },
    component: () => import(/* webpackChunkName: "reset-pwd" */ '../views/pages/reset-pwd.vue')
  },
  {
    path: '/403',
    meta: {
      title: '没有权限',
      noAuth: true
    },
    component: () => import(/* webpackChunkName: "403" */ '../views/pages/403.vue')
  },
  {
    path: '/404',
    meta: {
      title: '找不到页面',
      noAuth: true
    },
    component: () => import(/* webpackChunkName: "404" */ '../views/pages/404.vue')
  },
  { path: '/:path(.*)', redirect: '/404' }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  NProgress.start()
  const role = localStorage.getItem('ms_username')
  const permiss = usePermissStore()

  if (!role && to.meta.noAuth !== true) {
    next('/login')
  } else if (to.meta.permiss && !permiss.key.includes(to.meta.permiss)) {
    // 如果没有权限，则进入403
    next('/403')
  } else {
    next()
  }
})

router.afterEach(() => {
  NProgress.done()
})

export default router
